$(document).ready(function (){
    // 加载试卷列表
    function loadExamList() {
        $.ajax({
            url: '/student/exams',
            method: 'GET',
            success: function (data) {
                console.log(data)
                const examTableBody = $('#examTableBody');
                examTableBody.empty(); // 清空表格
                data.data.forEach(exam => {
                    const row = `<tr>
                        <td>${exam.title}</td>
                        <td>${exam.teacherName}</td>
                        <td>${exam.questionCount * exam.scorePerQuestion}</td>
                        <td>${exam.createdAt}</td>
                        <td>
                            ${exam.isSubmit === 0 ?
                        `<a href="#" class="btn btn-success btn-sm startExam" data-id="${exam.examId}">开始考试</a>` :
                        `<span class="text-muted">已参加考试</span>`}
                        </td>
                    </tr>`;
                    examTableBody.append(row);
                });
            },
            error: function () {
                alert('加载试卷列表失败！');
            }
        });
    }


    $(document).on("click", ".startExam", function() {
        var examId = $(this).data("id");

        // 异步请求试卷详情
        $.ajax({
            url: `/student/examDetails?id=${examId}`,
            method: 'GET',
            success: function (response) {
                if (response.code === 200) {
                    var exam = response.data;

                    // 更新试卷的基本信息
                    $('#examTitleDetail').text(exam.title);  // 试卷标题
                    $('#examCreator').text('出卷人: ' + exam.teacherName);  // 出卷人
                    $('#examTotalScore').text('总分: ' + (exam.questionCount * exam.scorePerQuestion));  // 总分
                    $('#examScorePerQuestion').text('每题分值: ' + exam.scorePerQuestion);  // 每题分值

                    // 填充试卷题目列表
                    var questionsList = $('#examQuestionsList');
                    questionsList.empty();  // 清空列表

                    exam.questions.forEach(function(question, index) {
                        var questionNumber = index + 1;
                        var questionId = question.questionId;  // 获取问题的唯一 ID
                        var optionA = question.optionA;  // 选项
                        var optionB = question.optionB;  // 选项
                        var optionC = question.optionC;  // 选项
                        var optionD = question.optionD;  // 选项

                        // 构造问题和选项
                        var questionHTML = `
                        <div class="mb-3" id="question_${questionId}">
                            <h5><strong>问题 ${questionNumber}: </strong>${question.questionText}</h5>
                            <div class="ms-4">
                                <input type="radio" name="question_${questionId}" value="A"> A: ${optionA} <br>
                                <input type="radio" name="question_${questionId}" value="B"> B: ${optionB} <br>
                                <input type="radio" name="question_${questionId}" value="C"> C: ${optionC} <br>
                                <input type="radio" name="question_${questionId}" value="D"> D: ${optionD} <br>
                            </div>
                        </div>
                    `;
                        questionsList.append(questionHTML);  // 添加到模态框中
                    });
                    // 设置 examId 到模态框的 data 属性中
                    $('#examModal').data('examId', examId);  // 假设 exam 对象有 id 字段
                    // 显示模态框
                    var examModal = new bootstrap.Modal(document.getElementById('examModal'));
                    examModal.show();
                } else {
                    alert('加载试卷详情失败');
                }
            },
            error: function () {
                alert('加载试卷详情失败');
            }
        });
    });



    $('#submitExamBtn').on('click', function() {
        // 收集所有问题的答案
        var answers = [];
        var isCompleted = true;  // 用于标记是否完成所有问题的回答

        $('#examQuestionsList .mb-3').each(function(index, questionDiv) {
            var questionId = $(questionDiv).attr('id').replace('question_', '');  // 获取问题的 ID
            var selectedOption = $(`input[name="question_${questionId}"]:checked`).val();

            if (selectedOption) {
                answers.push({ questionId: questionId, selectedOption: selectedOption });
            } else {
                isCompleted = false;  // 如果有问题没有回答，标记为未完成
                return false;  // 提前终止 `.each` 循环
            }
        });

        if (!isCompleted) {
            alert('请回答所有问题！');
            return;  // 如果有未回答的问题，停止执行后续代码
        }

        // 提交答案
        var examId = $('#examModal').data('examId');  // 获取当前考试的ID
        console.log(examId)
        $.ajax({
            url: `/student/submitExam`,
            method: 'POST',
            contentType: 'application/json',  // 发送 JSON 数据
            data: JSON.stringify({id: examId, answers: answers }),  // 将 answers 数组转换为 JSON 字符串
            success: function(response) {
                if (response.code === 200) {
                    alert('试卷提交成功！');
                    // Ensure the modal is correctly initialized and closed
                    var examModal = bootstrap.Modal.getInstance(document.getElementById('examModal'));
                    if (examModal) {
                        examModal.hide();  // 关闭模态框
                        loadExamList()
                    } else {
                        alert('无法关闭模态框');
                    }
                } else {
                    alert('提交失败！');
                }
            },
            error: function() {
                alert('提交试卷失败！');
            }
        });
    });


    // 加载以启动的试卷列表
    loadExamList();
});